//
//  AsyncCacheImageView.m
//  ymall
//
//  Created by yuike6 yuike6 on 12-2-8.
//  Copyright (c) 2012年 yuike. All rights reserved.
//

#import "AsyncCacheImageView.h"
#import "header.h"

@implementation AsyncCacheImageView
@synthesize currentUrl;
@synthesize delegate;

@synthesize downLoaderHelper = downLoaderHelper_;
@synthesize recvData = recvData_;

@synthesize spinner = spinner_;

-(void) dealloc
{
    [self.downLoaderHelper cancel];
    
    YRelease(indicator);    
    YRelease(currentUrl);
        
    YRelease(downLoaderHelper_);
    YRelease(recvData_);   
    
    YRelease(spinner_);
        
    [super dealloc];
}

- (void)setup
{  
    UIImage * spinnerImage = [UIImage imageNamed:@"=loading.png"];
    if (spinnerImage) 
    {    
        bDefaultWaitingControl = NO;
        if (!self.spinner) 
        {            
            ImageSpinner * spinner__ = [[ImageSpinner alloc] init];
            [spinner__ setCenter:self.boundsCenter];    
            [spinner__ setImage:spinnerImage];
            [spinner__ setFrame:CGRectMake(0.0f, 0.0f, spinnerImage.size.width, spinnerImage.size.height)];
            
            self.spinner = spinner__;
            YRelease(spinner__);
        }

        [self addSubview:self.spinner];
        [self bringSubviewToFront:self.spinner];
        YHIDEVIEW(self.spinner);
    }
    else
    {
        bDefaultWaitingControl = YES;
        YRelease(indicator);
        indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        indicator.center = [self boundsCenter];
        indicator.hidesWhenStopped = YES;
        [self addSubview:indicator];
    }
    
    
    DownloadHelper * tmp_downloadHelper_ = [[DownloadHelper alloc] init];
    [tmp_downloadHelper_ setDelegate:self];
    
    DownloadRecvDataMemory * data = [[[DownloadRecvDataMemory alloc] init] autorelease];
    self.recvData = data;
    if (self.recvData) 
    {
        [tmp_downloadHelper_ setData:self.recvData];
    }
    
    
    
    self.downLoaderHelper = tmp_downloadHelper_;
    YRelease(tmp_downloadHelper_);
    
	}

-(void) setFrame:(CGRect)frame
{
    [super setFrame:frame];
    if (bDefaultWaitingControl) 
    {
        indicator.center = [self boundsCenter];
    }
    else
    {
        self.spinner.center = [self boundsCenter];
    }    
}


- (id)initWithCoder:(NSCoder *)aDecoder
{
	if((self = [super initWithCoder:aDecoder]))
	{
        // Initialization code
		[self setup];
	}
	return self;
}

- (id)initWithImage:(UIImage *)anImage highlightedImage:(UIImage *)aHighlightedImage
{
	if((self = [super initWithImage:anImage 
				   highlightedImage:aHighlightedImage]))
	{
        // Initialization code
		[self setup];
	}
	return self;
}

- (id)initWithImage:(UIImage *)anImage
{
	if((self = [super initWithImage:anImage]))
	{
        // Initialization code
		[self setup];
	}
	return self;
}

- (id)initWithFrame:(CGRect)aFrame
{
    if((self = [super initWithFrame:aFrame]))
	{
        // Initialization code
		[self setup];
    }
    return self;
}


#pragma mark -
#pragma mark functions for loading images


- (BOOL)loadImageWithURL:(NSURL*)url 
			  parameters:(NSDictionary*)params 
  additionalHeaderFields:(NSDictionary*)headerFields 
		 timeoutInterval:(NSTimeInterval)timeout
{
	@synchronized(self)
	{        

        self.currentUrl = url;
           
        if (!self.currentUrl) {
            return FALSE;
        }
        if([self.currentUrl isFileURL])
        {
//            DebugLog(@"%@ is FileURL", url);
            NSData * _data = [[NSData alloc] initWithContentsOfURL:self.currentUrl];
            
            if (!_data) {
                return NO;
            }
            
            if (bDefaultWaitingControl) 
            {
                [indicator stopAnimating]; 
            }
            else
            {
                [self.spinner stopSpinnering];
                YHIDEVIEW(self.spinner);
            }    
             
            
            UIImage *image = [UIImage imageWithData:_data];  
            [self setImage:image];  
            [_data release];
            
            [delegate asyncImageView:self 
					 didReceiveImage:self.image 
							imageUrl:self.currentUrl];
            return YES;
        }        
        
		[self.downLoaderHelper cancel];	
		self.image = nil;
		
		//start indicator
		
        if (bDefaultWaitingControl) 
        {
            [indicator startAnimating]; 
        }
        else
        {
            [self.spinner startSpinnering];
            YSHOWVIEW(self.spinner);
        }    
        
        [[self recvData] setName:[url absoluteString]];
        [self.downLoaderHelper download:url];
        
        return TRUE;
	}
}


- (BOOL)loadImageWithURLString:(NSString*)urlString
					parameters:(NSDictionary*)params 
		additionalHeaderFields:(NSDictionary*)headerFields 
			   timeoutInterval:(NSTimeInterval)timeout
{
    
    NSString * decoderUrlString = [urlString urldecodedValue];
    
    NSString * encodingUrlString = [decoderUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	return [self loadImageWithURL:[NSURL URLWithString:encodingUrlString] 
					   parameters:params 
		   additionalHeaderFields:headerFields 
				  timeoutInterval:timeout];
}

- (void) didReceiveDataFinish: (NSData *) theData
{
    self.image = [UIImage imageWithData:theData];
			
    [delegate asyncImageView:self 
             didReceiveImage:self.image 
                    imageUrl:self.currentUrl];
           
    
    if (bDefaultWaitingControl) 
    {
        [indicator stopAnimating];
    }
    else
    {
        [self.spinner stopSpinnering];
        YHIDEVIEW(self.spinner);
    }    
    
    [self setNeedsLayout];       
    
}
- (void) didReceiveFilename: (NSString *) aName
{
    // 返回下载 url 的文件名， 如： a.png 
}

- (void) dataDownloadFailed: (NSString *) reason
{
    if (bDefaultWaitingControl) 
    {
        [indicator stopAnimating];
    }
    else
    {
        [self.spinner stopSpinnering];
        YHIDEVIEW(self.spinner);
    }    
    
    [self setNeedsLayout];
	
    [delegate asyncImageViewFailed:self imageUrl:self.currentUrl];
}

- (void) dataDownloadAtPercent: (NSNumber *) aPercent
{
//    float process = [aPercent floatValue] * 100;
//    DebugLog(@"%.0f", process);
}

@end
